package com.kchouse.homepage;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.kchouse.MainActivity;
import com.kchouse.StartActivity;
import com.kchouse.bean.CashCouponItem;
import com.kchouse.bean.CouponItem;
import com.kchouse.bean.MerchantItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.R;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.union.MerchantDetailsActivity;
import com.squareup.picasso.Picasso;

import java.text.DecimalFormat;
import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;


public class CouponsActivity extends BaseActivity implements View.OnClickListener {

    private CouponsActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private ListView lv_sbitem;
    private Intent intent = new Intent();
    private LvSbAdapter sbadapter;
    private RadioGroup rg_item;
    private RadioButton rb_item1;
    private RadioButton rb_item2;
    private View ll_cashcoupon;
    private View ll_coupon;
    private ListView lv_item;
    private ArrayList<CashCouponItem> listcashcoupon = new ArrayList<>();
    private ArrayList<CouponItem> listcoupon = new ArrayList<>();
    private ListView lv_cashcoupon;
    private TextView tv_addpage;
    private EditText et_searchsb;
    private int page = 1;
    private Integer totalCount;
    private ArrayList<MerchantItem> listmerchant = new ArrayList<>();
    private MineCashCouponsAdapter adpterMineCoup;
    private boolean isLogin = false;
    private View rl_search;
    private CouponsAdapter coupadpter;
    private EditText et_search;
    private View rl_search2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coupons);

        mContent = this;
        intiData();
        intiView();
    }


    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("卡券");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        lv_sbitem = (ListView) findViewById(R.id.lv_sbitem);
        sbadapter = new LvSbAdapter();
        lv_sbitem.setAdapter(sbadapter);
        lv_sbitem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MerchantItem item = listmerchant.get(position);
//                ToastUtils.getInstanc(mContent).showToast("商家id："+item.getId());

                intent.putExtra("Merchantid", item.getId());
                intent.setClass(mContent, MerchantDetailsActivity.class);
                startActivity(intent);
            }
        });
        ll_cashcoupon = findViewById(R.id.ll_cashcoupon);
        ll_coupon = findViewById(R.id.ll_coupon);


        lv_cashcoupon = (ListView) findViewById(R.id.lv_cashcoupon);
        adpterMineCoup = new MineCashCouponsAdapter();
        lv_cashcoupon.setAdapter(adpterMineCoup);
        lv_cashcoupon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                CashCouponItem data = listcashcoupon.get(position);
                //进入现金券详情
                intent.putExtra("data", data);
                intent.putExtra("coupon", "现金券");
                intent.setClass(mContent, CouponDetailsActivity.class);
                startActivity(intent);
            }
        });

        tv_addpage = (TextView) findViewById(R.id.tv_addpage);
        tv_addpage.setOnClickListener(this);
        et_searchsb = (EditText) findViewById(R.id.et_searchsb);
        et_searchsb.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    ToastUtils.getInstanc(mContent).showToast("搜索");
                    if (!TextUtils.isEmpty(et_searchsb.getText().toString())) {
                        page = 1;
                        listmerchant.clear();
                        GetMerchant(et_searchsb.getText().toString(), page);
                        tv_addpage.setVisibility(View.GONE);
                        et_searchsb.setText("");
                    }
                }
                return false;
            }
        });

        rl_search = findViewById(R.id.rl_search);
        rl_search.setOnClickListener(this);
        lv_item = (ListView) findViewById(R.id.lv_item);
        coupadpter = new CouponsAdapter();
        lv_item.setAdapter(coupadpter);
        lv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                ToastUtils.getInstanc(mContent).showToast("暂未开通");
//                CouponItem item = listcoupon.get(position);
//                        intent.putExtra("coupon","优惠券");
//                        intent.setClass(getActivity(),CouponDetailsActivity.class);
//                        startActivity(intent);
                CouponItem data = listcoupon.get(position);
                //进入优惠券
                intent.putExtra("data", data);
                intent.putExtra("coupon", "优惠券");
                intent.setClass(mContent, CouponDetailsActivity.class);
                startActivity(intent);


            }
        });

        et_search = (EditText) findViewById(R.id.et_search);
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    ToastUtils.getInstanc(mContent).showToast("搜索");
                    if (!TextUtils.isEmpty(et_searchsb.getText().toString())) {
//                        page = 1;
                        listcoupon.clear();
                        GetCoupons(et_search.getText().toString());
//                        tv_addpage.setVisibility(View.GONE);
                        et_search.setText("");
                    }
                }
                return false;
            }
        });
        rl_search2 = findViewById(R.id.rl_search2);
        rl_search2.setOnClickListener(this);

        intiRG();

    }


    class CouponsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listcoupon.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            CouponItem item = listcoupon.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_coupons_item, null);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getName());
            TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
            tv_merchantName.setText(item.getMerchantShortName());

            if (item.isFollowStatus()) {
                tv_merchantName.setTextColor(getResources().getColor(R.color.text_main));
                tv_merchantName.setTypeface(Typeface.DEFAULT_BOLD);

            } else {
                tv_merchantName.setTypeface(Typeface.DEFAULT);
                tv_merchantName.setTextColor(getResources().getColor(R.color.colorblack));
            }
            TextView tv_inventory = (TextView) view.findViewById(R.id.tv_inventory);
            tv_inventory.setText("剩余数量：" + item.getInventory());
            ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
            Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
            TextView tv_distance = (TextView) view.findViewById(R.id.tv_distance);
            double distance = item.getDistance() / 1000;
            DecimalFormat df = new DecimalFormat("0.##");
            String st = df.format(distance);
            tv_distance.setText(st + "km");
//            intiDistance(tv_distance, item);
            TextView tv_time = (TextView) view.findViewById(R.id.tv_time);
            tv_time.setText("有效期：至" + item.getEndTime());
            return view;
        }
    }

    /**
     * 距离计算
     *
     * @param
     * @param item
     */
    private void intiDistance(TextView tv, CouponItem item) {
        LatLng startLatlng = new LatLng(StartActivity.mLatitude, StartActivity.mLongitude);
        LatLng endLatlng = new LatLng(Double.valueOf(item.getLatitude()), Double.valueOf(item.getLongitude()));

        double distance = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
        distance = distance / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        tv.setText(st + "km");
    }


    /**
     * 初始化单选框
     */
    private void intiRG() {
        rg_item = (RadioGroup) findViewById(R.id.rg_item);
        rb_item1 = (RadioButton) findViewById(R.id.rb_item1);
        rb_item1.setChecked(true);
        rb_item2 = (RadioButton) findViewById(R.id.rb_item2);
        rg_item.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_item1) {
//                    ToastUtils.getInstanc(mContent).showToast("现金券");
                    ll_cashcoupon.setVisibility(View.VISIBLE);
                    ll_coupon.setVisibility(View.GONE);
                } else {
//                    ToastUtils.getInstanc(mContent).showToast("优惠券");
                    ll_cashcoupon.setVisibility(View.GONE);
                    ll_coupon.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void intiData() {

//        GetMerchant("", page);

//        GetCoupons("");
    }


    /**
     * 获取优惠券信息
     */
    private void GetCoupons(String merchantName) {
        String url = API.GetCoupons;
//        String url = API.GetCoupons+"?merchantName="+merchantName;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("merchantName", merchantName);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    listcoupon.clear();
                    String datastr = json.getString("data");
                    JSONObject couliststr = JSONObject.parseObject(datastr);
                    listcoupon.addAll(JSONObject.parseArray(couliststr.getString("couponTemplateList"), CouponItem.class));
                    coupadpter.notifyDataSetChanged();

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);

//                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    } else {
//                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    }

//                    checkLogin();
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);


            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 支持商家
     */
    private void GetMerchant(String name, int page) {
        String url = API.GetFreeMerchant;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
//        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("token", MineFragment.userid);
        params.addFormDataPart("name", name);
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listmerchant.size() == totalCount)//总个数已满
                    {
//                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(mContent).showToast("暂无更多");
                        tv_addpage.setVisibility(View.GONE);
                    } else {
                        listmerchant.addAll(JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class));
                    }
                    sbadapter.notifyDataSetChanged();
                    if (JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class).size() == 0) {
                        ToastUtils.getInstanc(mContent).showToast("暂无更多");
                        tv_addpage.setVisibility(View.GONE);
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        GetCashCoupons();
        GetCoupons("");
    }

    /**
     * 获取现金券信息
     */
    private void GetCashCoupons() {
        String url = API.GetCashCoupons;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("token", MineFragment.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
//                    String datastr = json.getString("data");
//                    data = JSONObject.parseObject(datastr, CashCouponItem.class);
//                    Picasso.with(mContent).load(data.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_icon);
//                    tv_name.setText(data.getCashTemplateName());
//                    tv_num.setText("剩余数量："+data.getNum());

                    listcashcoupon.clear();
                    String datastr = json.getString("data");
                    CashCouponItem data = JSONObject.parseObject(datastr, CashCouponItem.class);
                    listcashcoupon.add(data);
                    adpterMineCoup.notifyDataSetChanged();

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);

//                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    } else {
//                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    }

//                    checkLogin();
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);


            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 校验登录状态
     *
     * @return
     */
    private boolean checkLogin() {
        // 如果未登录都进入登录界面
        if (!isLogin) {
            intent.setClass(mContent, LoginPhoneActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    class MineCashCouponsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listcashcoupon.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CashCouponItem item = listcashcoupon.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_cashcoupon_item, null);
            ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
            Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_icon);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getCashTemplateName());
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            tv_num.setText("剩余数量：" + item.getNum() + "张");
            return view;
        }
    }


    /**
     * 商家服务列表
     */
    class LvSbAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listmerchant.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = getLayoutInflater().inflate(R.layout.lv_sb_item2, null);
            MerchantItem item = listmerchant.get(position);

            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getShortName());

            if (item.isFollowStatus()) {
                tv_name.setTextColor(getResources().getColor(R.color.text_main));
                tv_name.setTypeface(Typeface.DEFAULT_BOLD);

            } else {
                tv_name.setTypeface(Typeface.DEFAULT);
                tv_name.setTextColor(getResources().getColor(R.color.colorblack));
            }
            ImageView iv_vip = (ImageView) view.findViewById(R.id.iv_vip);
            ImageView iv_security = (ImageView) view.findViewById(R.id.iv_security);
            if (item.getVipStatus() == 1) {
                iv_vip.setVisibility(View.VISIBLE);
            } else {
                iv_vip.setVisibility(View.GONE);
            }
            if (item.getGuaranteeStatus() == 1) {
                iv_security.setVisibility(View.VISIBLE);
            } else {
                iv_security.setVisibility(View.GONE);
            }
            return view;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_addpage:
                page = page + 1;
                GetMerchant("", page);
                break;
            case R.id.rl_search://搜索现金券支持商家
                page = 1;
                listmerchant.clear();
                GetMerchant(et_searchsb.getText().toString(), page);
                tv_addpage.setVisibility(View.GONE);
                et_searchsb.setText("");
                break;
            case R.id.rl_search2://搜索优惠券商家
                listcoupon.clear();
                GetCoupons(et_search.getText().toString());
                et_search.setText("");
                break;

        }
    }
}
